/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.audit.service.api.AuditService;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.generator.GetHardwareIdFailedException;
import com.koron.common.generator.InvalidSystemClockException;
import com.koron.common.util.PdfUtil;
import com.koron.common.web.Util;
import com.koron.scene.domain.*;
import com.koron.scene.mapper.DangerousOperationRelationMapper;
import com.koron.scene.mapper.OperationActivityMapper;
import com.koron.scene.service.api.OperationActivityService;
import com.koron.scene.utils.BusinessCode;
import com.koron.scene.utils.OperationTicketPdfUtil;
import com.koron.workflow.service.api.WorkflowService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作业活动服务实现类
 *
 * @author lwl
 * @since 2023/4/10
 */
@Service
public class OperationActivityServiceImpl implements OperationActivityService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(OperationActivityServiceImpl.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private AuditService auditService;

    @Autowired
    private WorkflowService flowService;

    @Autowired
    private Util util;

    @Autowired
    private OperationTicketPdfUtil operationTicketPdfUtil;

    private Map<Integer, String> templateKeys = new HashMap<Integer, String>() {
        {
            this.put(1, "operation_ticket1_creation");
            this.put(2, "operation_ticket2_creation");
        }
    };

    private Map<String, String> operationTicketTypes = new HashMap<String, String>() {
        {
            this.put("0", "动火作业票");
            this.put("1", "高处作业票");
            this.put("2", "临时用电作业票");
            this.put("3", "起重吊装作业票");
            this.put("4", "有限空间作业票");
        }
    };

    public static String PROCESSTASK1 = "Process-task1";
    public static String PROCESSTASK2 = "Process-task2";
    public static String PROCESSTASK3 = "Process-task3";
    public static String PROCESSTASK4 = "Process-task4";

    @Override
    @TaskAnnotation("list")
    public MessageBean list(SessionFactory factory, OperationActivityQuery bean) {
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "获取作业活动列表成功", null);
        // 是否包含子级
        Integer containSub = bean.getContainSub();
        if (containSub != null && containSub == 1) {
            bean.setCorpCode(util.getDeptCodes(bean.getCorpCode()));
        } else {
            bean.setCorpCode("('" + bean.getCorpCode() + "')");
        }
        // 查询作业活动列表
        int offset = (bean.getPage() - 1) * bean.getPageSize();
        bean.setOffset(offset);
        bean.setOperationTicketType(StringUtils.isNotEmpty(operationTicketTypes.get(bean.getOperationTicketType())) ? operationTicketTypes.get(bean.getOperationTicketType()) : "");
        // 查询作业活动总记录数
        Integer totalNumber = mapper.selectCount(bean);
        List<OperationActivity> operationActivities = Optional.of(mapper.selectList(bean)).orElse(new ArrayList<>());
        // 构造分页数据
        int pageSize = bean.getPageSize();
        Integer totalPage = (totalNumber > pageSize) ? (totalNumber % pageSize == 0 ? totalNumber / pageSize : totalNumber / pageSize + 1) : 1;
        DataBean<OperationActivity> dataBean = new DataBean<>();
        dataBean.setList(operationActivities);
        dataBean.setTotalPage(totalPage);
        dataBean.setTotalNumber(totalNumber);
        dataBean.setPageSize(pageSize);
        msg.setData(dataBean);
        return msg;
    }

    @Override
    @TaskAnnotation("add")
    public MessageBean add(SessionFactory factory, OperationActivity bean, StaffBean user) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "新增活动作业成功", String.class);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);

        try {
            // 新增作业活动记录
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            bean.setAddUser(user.getCode());
            bean.setAddTime(new Date());
            bean.setAddUserName(user.getName());
            Integer column = mapper.insert(bean);
            if (column > 0) {
                msg.setData(bean.getId());
            }
        } catch (Exception e) {
            logger.error("新增活动作业失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "新增活动作业失败", null);
        }
        return msg;
    }

    @Override
    @TaskAnnotation("update")
    public MessageBean update(SessionFactory factory, OperationActivity bean, StaffBean user) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "更新活动作业成功", String.class);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);

        try {
            // 更新作业活动记录
            bean.setUpdateUser(user.getCode());
            bean.setUpdateTime(new Date());
            bean.setUpdateUserName(user.getName());
            Integer column = mapper.update(bean);
            if (column > 0) {
                msg.setData(bean.getId());
            }
        } catch (Exception e) {
            logger.error("更新活动作业失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "更新活动作业失败", null);
        }
        return msg;
    }

    @Override
    @TaskAnnotation("delete")
    public MessageBean delete(SessionFactory factory, String id) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除活动作业成功", String.class);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);

        try {
            OperationTicketQuery query = new OperationTicketQuery();
            query.setOperationActivityId(id);
            Integer column = mapper.selectOperationTicketCount(query);
            if (column > 0) {
                logger.error("作业活动涉及多张作业票，不能删除");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "作业活动涉及多张作业票，不能删除", null);
            }

            // 删除作业活动
            mapper.deleteById(id);

        } catch (Exception e) {
            logger.error("删除活动作业失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "删除活动作业失败", null);
        }
        return msg;
    }

    @Override
    @TaskAnnotation("detail")
    public MessageBean detail(SessionFactory factory, String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询活动作业成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        if (StringUtils.isEmpty(id)) {
            logger.error("id 不能为空");
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "id 不能为空", null);
        }
        OperationActivity operationActivity = mapper.selectById(id);
        msg.setData(operationActivity);
        return msg;
    }


    @Override
    @TaskAnnotation("queryOperationTicketById")
    public MessageBean queryOperationTicketById(SessionFactory factory, String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "获取作业活动涉及作业票详情成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);

        try {
            OperationTicket operationTicket = mapper.selectOperationTicketById(id);
            if (operationTicket == null) {
                logger.error("作业票数据不存在");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "作业票数据不存在", null);
            }

            // 查询气体分析
            if (operationTicket.getIncludeGas() != null && operationTicket.getIncludeGas() == 1) {
                List<GasAnalysis> gasAnalyses = Optional.of(mapper.selectGasAnalysisByOperationTicketId(id)).orElse(new ArrayList<>());
                operationTicket.getGasAnalysisList().addAll(gasAnalyses);
            }

            // 查询安全措施
            List<SafetyMeasure> safetyMeasures = Optional.of(dangerousOperationRelationMapper.getSafetyByDangerousId(id)).orElse(new ArrayList<>());
            operationTicket.getSafetyMeasureList().addAll(safetyMeasures);

            msg.setData(operationTicket);
        } catch (Exception e) {
            logger.error("获取作业活动涉及作业票详情失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "获取作业活动涉及作业票详情失败", null);
        }
        return msg;
    }

    @Override
    public MessageBean exportOperationTicket(SessionFactory factory, OutputStream os, String id) {
        MessageBean messageBean = queryOperationTicketById(factory, id);
        if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
            OperationTicket operationTicket = (OperationTicket) messageBean.getData();
            operationTicketPdfUtil.writeToOs(os, operationTicket);
        } else {
            // 创建Document
            Document document = new Document();
            PdfWriter writer = null;
            try {
                writer = PdfWriter.getInstance(document, os);
                // 打开document
                document.open();
                document.add(new Paragraph("作业票下载失败。", PdfUtil.getFont(8, Font.NORMAL)));
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            } finally {
                document.close();
                writer.close();
            }
        }
        return null;
    }

    public MessageBean addOperationTicketByQrCode(SessionFactory factory, HttpServletRequest request, OperationTicket bean, StaffBean user, String approver) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "二维码填报作业票成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
        try {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            List<String> approverList = new ArrayList<>();
            if (StringUtils.isNotEmpty(approver)) {
                approverList.addAll(Arrays.asList(approver.split(",")));
            }

            // 作业票实体赋值
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            bean.setOperationCode(getCode(factory));
            bean.setAddUser(user.getCode());
            bean.setAddTime(new Date());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());

            if (request.getParameter("attachmentFileSize") != null && Integer.parseInt(request.getParameter("attachmentFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("attachmentFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("attachmentFiles" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                bean.setAttachmentFiles(files);
            }

            List<String> keepList = new ArrayList<>();
            if (null != bean.getAttachmentFiles() && bean.getAttachmentFiles().length > 0) {
                for (MultipartFile file : bean.getAttachmentFiles()) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    keepList.add(url + "#" + fileName);
                }
                if (keepList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepList));
                }
            }
            // 作业票编制人签字
            if (request.getParameter("editOperationFileSize") != null && Integer.parseInt(request.getParameter("editOperationFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("editOperationFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("editOperationFile" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        keepList.add(url + "#" + fileName);
                    }
                    if (keepList.size() > 0) {
                        bean.setEditOperationSignature(new Gson().toJson(keepList));
                    }
                }
            }
            // 处理气体分析
            if (bean.getOperationTicketType().equals("0") || bean.getOperationTicketType().equals("4")) {
                if (null != bean.getIncludeGas() && bean.getIncludeGas() == 1 && !StringUtils.isEmpty(bean.getGasAnalyses())) {
                    List<GasAnalysis> gasAnalyses = JSONObject.parseArray(bean.getGasAnalyses(), GasAnalysis.class);
                    for (GasAnalysis gasAnalysis : gasAnalyses) {
                        gasAnalysis.setOperationTicketId(bean.getId());
                        gasAnalysis.setId(DefaultIdGenerator.getInstance().generateLongId());
                        mapper.insertGasGasAnalysis(gasAnalysis);
                    }
                }
            } else {
                bean.setIncludeGas(0);
            }

            // 处理安全措施
            if (!StringUtils.isEmpty(bean.getSafetyMeasures())) {
                List<SafetyMeasure> safetyMeasures = JSONObject.parseArray(bean.getSafetyMeasures(), SafetyMeasure.class);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasures) {
                            safetyMeasure.setFiles(standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo()));
                        }
                    }
                }
                if (null != safetyMeasures && safetyMeasures.size() > 0) {
                    for (SafetyMeasure safetyMeasure : safetyMeasures) {
                        List<MultipartFile> files = safetyMeasure.getFiles();
                        if (null != files && files.size() > 0) {
                            for (MultipartFile file : files) {
                                String url = clientWrapper.uploadFile(file);
                                //获得文件名
                                String fileName = file.getOriginalFilename();
                                safetyMeasure.getKeepList().add(url + "#" + fileName);
                            }
                        }
                        List<String> keepList1 = safetyMeasure.getKeepList();
                        if (null != keepList1 && keepList1.size() > 0) {
                            safetyMeasure.setAttachment(new Gson().toJson(keepList1));
                        }
                        safetyMeasure.setId(DefaultIdGenerator.getInstance().generateLongId());
                        safetyMeasure.setDangerousOperationId(bean.getId());
                    }
                    dangerousOperationRelationMapper.batchInsertSafe(safetyMeasures);
                }
            }

            // 插入作业票记录
            Integer value = mapper.insertOperationTicket(bean);
            if (value > 0 && bean.getStatus() == 1) {
                String templateKey = getTemplateKeyByQrCode(bean.getOperationTicketType());
                if (null != templateKey) {
                    Boolean startAudit = startAuditByQrCode(bean, user, approverList, "流程待审批", "作业活动-作业票流程", templateKey);
                    if (!startAudit) {
                        factory.close(false);
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("作业活动-作业票流程启动失败");
                        return msg;
                    } else {
                        factory.close();
                        msg.setCode(BusinessCode.SUCCESS.getCode());
                        msg.setDescription("作业活动-作业票提交成功");
                        msg.setData(value);
                        return msg;
                    }
                }
            }
            if (value > 0) {
                OperationTicketQuery query = new OperationTicketQuery();
                query.setOperationActivityId(bean.getOperationActivityId());
                List<OperationTicket> list = mapper.selectOperationTicket(query);
                if (list != null && list.size() > 0) {
                    String collect = list.stream().map(OperationTicket::getOperationTicketTypeName).distinct().collect(Collectors.joining(","));
                    mapper.updateOperationActivityType(bean.getOperationActivityId(), collect);
                }
            }
            return msg;
        } catch (Exception e) {
            logger.error("二维码填报作业票失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "二维码填报作业票失败", null);
        }
    }

    public MessageBean updateOperationTicketByQrCode(SessionFactory factory, HttpServletRequest request, OperationTicket bean, StaffBean user, String approver) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "二维码修改作业票成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);

        try {
            List<String> approverList = new ArrayList<>();
            if (StringUtils.isNotEmpty(approver)) {
                approverList.addAll(Arrays.asList(approver.split(",")));
            }

            OperationTicket operationTicket = mapper.selectOperationTicketById(bean.getId());
            if (operationTicket == null) {
                logger.error("作业票数据不存在");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "作业票数据不存在", null);
            }
            if (operationTicket.getStatus() != 0) {
                logger.error("非草稿状态不能修改");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "非草稿状态不能删除", null);
            }

            // 气体分析
            if (bean.getOperationTicketType().equals("0") || bean.getOperationTicketType().equals("4")) {
                if (null != bean.getIncludeGas() && bean.getIncludeGas() == 1 && !StringUtils.isEmpty(bean.getGasAnalyses())) {
                    // 删除原有数据
                    mapper.deleteGasAnalysisByOperationTicketId(bean.getId());
                    //添加气体分析数据
                    List<GasAnalysis> gasAnalyses = JSONObject.parseArray(bean.getGasAnalyses(), GasAnalysis.class);
                    for (GasAnalysis gasAnalysis : gasAnalyses) {
                        gasAnalysis.setOperationTicketId(bean.getId());
                        gasAnalysis.setId(DefaultIdGenerator.getInstance().generateLongId());
                        mapper.insertGasGasAnalysis(gasAnalysis);
                    }
                }
            } else {
                bean.setIncludeGas(0);
            }

            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            // 处理安全措施
            if (!StringUtils.isEmpty(bean.getSafetyMeasures())) {
                List<SafetyMeasure> safetyMeasures = JSONObject.parseArray(bean.getSafetyMeasures(), SafetyMeasure.class);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasures) {
                            List<MultipartFile> files = standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo());
                            if (files.size() > 0) {
                                safetyMeasure.setFiles(files);
                            }
                        }
                    }
                }
                bean.setSafetyMeasureList(safetyMeasures);
            }

            if (bean.getSafetyMeasureList() != null && bean.getSafetyMeasureList().size() > 0) {
                for (SafetyMeasure measure : bean.getSafetyMeasureList()) {
                    List<MultipartFile> files = measure.getFiles();
                    if (null != files && files.size() > 0) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            //获得文件名
                            String fileName = file.getOriginalFilename();
                            measure.getKeepList().add(url + "#" + fileName);
                        }
                    }
                    // 保留的附件地址
                    String keepFiles = measure.getKeepFiles();
                    if (StringUtils.isNotEmpty(keepFiles)) {
                        List<String> keepFileList = Arrays.asList(keepFiles.split(","));
                        if (keepFileList.size() > 0) {
                            measure.getKeepList().addAll(keepFileList);
                        }
                    }
                    List<String> keepList = measure.getKeepList();
                    if (null != keepList && keepList.size() > 0) {
                        measure.setAttachment(new Gson().toJson(keepList));
                    } else {
                        measure.setAttachment("");
                    }
                    // 删除的附件地址
                    String delFiles = measure.getDelFiles();
                    if (StringUtils.isNotEmpty(delFiles)) {
                        List<String> delFileList = Arrays.asList(delFiles.split(","));
                        if (delFileList.size() > 0) {
                            for (String delFile : delFileList) {
                                clientWrapper.deleteFile(delFile.split("#")[0]);
                            }
                        }
                    }
                    measure.setId(DefaultIdGenerator.getInstance().generateLongId());
                    measure.setDangerousOperationId(bean.getId());
                }
            }
            // 更新安全措施，先删除原有数据，再重新添加
            dangerousOperationRelationMapper.deleteSafeByDangerousOperationId(bean.getId());
            dangerousOperationRelationMapper.batchInsertSafe(bean.getSafetyMeasureList());

            // 处理新增附件
            if (request.getParameter("attachmentFileSize") != null && Integer.parseInt(request.getParameter("attachmentFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("attachmentFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("attachmentFiles" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                bean.setAttachmentFiles(files);
            }

            if (null != bean.getAttachmentFiles() && bean.getAttachmentFiles().length > 0) {
                for (MultipartFile file : bean.getAttachmentFiles()) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    bean.getKeepList().add(url + "#" + fileName);
                }
            }
            // 要保留的附件管理
            String keepFiles = bean.getKeepFiles();
            if (StringUtils.isNotEmpty(keepFiles)) {
                String[] keepArray = keepFiles.split(",");
                bean.getKeepList().addAll(Arrays.asList(keepArray));
            }
            List<String> keepList = bean.getKeepList();
            if (null != keepList && keepList.size() > 0) {
                bean.setAttachment(new Gson().toJson(keepList));
            }
            // 删除的附件地址
            String delFiles = bean.getDelFiles();
            if (StringUtils.isNotEmpty(delFiles)) {
                String[] delArray = delFiles.split(",");
                for (String delUrl : delArray) {
                    clientWrapper.deleteFile(delUrl.split("#")[0]);
                }
            }
            // 作业票编制人签字
            if (request.getParameter("editOperationFileSize") != null && Integer.parseInt(request.getParameter("editOperationFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("editOperationFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("editOperationFile" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        keepList.add(url + "#" + fileName);
                    }
                    if (keepList.size() > 0) {
                        bean.setEditOperationSignature(new Gson().toJson(keepList));
                    }
                }
            }
            // 更新作业票记录
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(new Date());
            Integer value = factory.getMapper(OperationActivityMapper.class).updateOperationTicket(bean);

            if (value > 0 && bean.getStatus() == 1) {
                String templateKey = getTemplateKeyByQrCode(bean.getOperationTicketType());
                // 启动流程
                if (null == templateKey) {
                    factory.close();
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("未找到流程模板");
                    return msg;
                }
                Boolean startAudit = startAuditByQrCode(bean, user, approverList, "流程待审批", "作业活动-作业票流程", templateKey);
                if (!startAudit) {
                    deleteKeepFile(bean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("作业活动-作业票流程启动失败");
                    return msg;
                } else {
                    deleteDelFile(bean);
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("作业活动-作业票提交成功");
                    msg.setData(value);
                    return msg;
                }
            }
            if (value > 0) {
                OperationTicketQuery query = new OperationTicketQuery();
                query.setOperationActivityId(bean.getOperationActivityId());
                List<OperationTicket> list = mapper.selectOperationTicket(query);
                if (list != null && list.size() > 0) {
                    String collect = list.stream().map(OperationTicket::getOperationTicketTypeName).distinct().collect(Collectors.joining(","));
                    mapper.updateOperationActivityType(bean.getOperationActivityId(), collect);
                }
            }
        } catch (Exception e) {
            logger.error("二维码修改作业票失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "二维码修改作业票失败", null);
        }
        return msg;
    }

    public MessageBean addOperationTicket(SessionFactory factory, HttpServletRequest request, OperationTicket bean, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "新增作业票成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
        try {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            // 作业票实体赋值
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            bean.setOperationCode(getCode(factory));
            bean.setAddUser(user.getCode());
            bean.setAddTime(new Date());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());

            if (request.getParameter("attachmentFileSize") != null && Integer.parseInt(request.getParameter("attachmentFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("attachmentFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("attachmentFiles" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                bean.setAttachmentFiles(files);
            }

            List<String> keepList = new ArrayList<>();
            if (null != bean.getAttachmentFiles() && bean.getAttachmentFiles().length > 0) {
                for (MultipartFile file : bean.getAttachmentFiles()) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    keepList.add(url + "#" + fileName);
                }
                if (keepList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepList));
                }
            }
            if (request.getParameter("editOperationFileSize") != null && Integer.parseInt(request.getParameter("editOperationFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("editOperationFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("editOperationFile" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        keepList.add(url + "#" + fileName);
                    }
                    if (keepList.size() > 0) {
                        bean.setEditOperationSignature(new Gson().toJson(keepList));
                    }
                }
            }
            // 处理气体分析
            if (bean.getOperationTicketType().equals("0") || bean.getOperationTicketType().equals("4")) {
                if (null != bean.getIncludeGas() && bean.getIncludeGas() == 1 && !StringUtils.isEmpty(bean.getGasAnalyses())) {
                    List<GasAnalysis> gasAnalyses = JSONObject.parseArray(bean.getGasAnalyses(), GasAnalysis.class);
                    for (GasAnalysis gasAnalysis : gasAnalyses) {
                        gasAnalysis.setOperationTicketId(bean.getId());
                        gasAnalysis.setId(DefaultIdGenerator.getInstance().generateLongId());
                        mapper.insertGasGasAnalysis(gasAnalysis);
                    }
                }
            } else {
                bean.setIncludeGas(0);
            }

            // 处理安全措施
            if (!StringUtils.isEmpty(bean.getSafetyMeasures())) {
                List<SafetyMeasure> safetyMeasures = JSONObject.parseArray(bean.getSafetyMeasures(), SafetyMeasure.class);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasures) {
                            safetyMeasure.setFiles(standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo()));
                        }
                    }
                }
                if (null != safetyMeasures && safetyMeasures.size() > 0) {
                    for (SafetyMeasure safetyMeasure : safetyMeasures) {
                        List<MultipartFile> files = safetyMeasure.getFiles();
                        if (null != files && files.size() > 0) {
                            for (MultipartFile file : files) {
                                String url = clientWrapper.uploadFile(file);
                                //获得文件名
                                String fileName = file.getOriginalFilename();
                                safetyMeasure.getKeepList().add(url + "#" + fileName);
                            }
                        }
                        List<String> keepList1 = safetyMeasure.getKeepList();
                        if (null != keepList1 && keepList1.size() > 0) {
                            safetyMeasure.setAttachment(new Gson().toJson(keepList1));
                        }
                        safetyMeasure.setId(DefaultIdGenerator.getInstance().generateLongId());
                        safetyMeasure.setDangerousOperationId(bean.getId());
                    }
                    dangerousOperationRelationMapper.batchInsertSafe(safetyMeasures);
                }
            }

            // 插入作业票记录
            Integer value = mapper.insertOperationTicket(bean);
            if (value > 0 && bean.getStatus() == 1) {
                String templateKey = getTemplateKey(bean.getOperationTicketType());
                if (null != templateKey) {
                    Boolean startAudit = startAudit(bean, user, "流程待审批", "作业活动-作业票流程", templateKey);
                    if (!startAudit) {
                        factory.close(false);
                        msg.setCode(BusinessCode.FAILURE.getCode());
                        msg.setDescription("作业活动-作业票流程启动失败");
                        return msg;
                    } else {
                        factory.close();
                        msg.setCode(BusinessCode.SUCCESS.getCode());
                        msg.setDescription("作业活动-作业票提交成功");
                        msg.setData(value);
                        return msg;
                    }
                }
            }
            if (value > 0) {
                OperationTicketQuery query = new OperationTicketQuery();
                query.setOperationActivityId(bean.getOperationActivityId());
                List<OperationTicket> list = mapper.selectOperationTicket(query);
                if (list != null && list.size() > 0) {
                    String collect = list.stream().map(OperationTicket::getOperationTicketTypeName).distinct().collect(Collectors.joining(","));
                    mapper.updateOperationActivityType(bean.getOperationActivityId(), collect);
                }
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error("新增作业票失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "新增作业票失败", null);
        }
    }

    public MessageBean updateOperationTicket(SessionFactory factory, HttpServletRequest request, OperationTicket bean, StaffBean user) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "修改作业票成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);

        try {
            OperationTicket operationTicket = mapper.selectOperationTicketById(bean.getId());
            if (operationTicket == null) {
                logger.error("作业票数据不存在");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "作业票数据不存在", null);
            }
            if (operationTicket.getStatus() != 0) {
                logger.error("非草稿状态不能修改");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "非草稿状态不能修改", null);
            }

            // 处理气体分析
            if (bean.getOperationTicketType().equals("0") || bean.getOperationTicketType().equals("4")) {
                if (null != bean.getIncludeGas() && bean.getIncludeGas() == 1 && !StringUtils.isEmpty(bean.getGasAnalyses())) {
                    // 删除原有数据
                    mapper.deleteGasAnalysisByOperationTicketId(bean.getId());
                    //添加气体分析数据
                    List<GasAnalysis> gasAnalyses = JSONObject.parseArray(bean.getGasAnalyses(), GasAnalysis.class);
                    for (GasAnalysis gasAnalysis : gasAnalyses) {
                        gasAnalysis.setOperationTicketId(bean.getId());
                        gasAnalysis.setId(DefaultIdGenerator.getInstance().generateLongId());
                        mapper.insertGasGasAnalysis(gasAnalysis);
                    }
                }
            } else {
                bean.setIncludeGas(0);
            }

            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            // 处理安全措施
            if (!StringUtils.isEmpty(bean.getSafetyMeasures())) {
                List<SafetyMeasure> safetyMeasures = JSONObject.parseArray(bean.getSafetyMeasures(), SafetyMeasure.class);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasures) {
                            List<MultipartFile> files = standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo());
                            if (files.size() > 0) {
                                safetyMeasure.setFiles(files);
                            }
                        }
                    }
                }
                bean.setSafetyMeasureList(safetyMeasures);
            }

            if (bean.getSafetyMeasureList() != null && bean.getSafetyMeasureList().size() > 0) {
                for (SafetyMeasure measure : bean.getSafetyMeasureList()) {
                    List<MultipartFile> files = measure.getFiles();
                    if (null != files && files.size() > 0) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            //获得文件名
                            String fileName = file.getOriginalFilename();
                            measure.getKeepList().add(url + "#" + fileName);
                        }
                    }
                    // 保留的附件地址
                    String keepFiles = measure.getKeepFiles();
                    if (StringUtils.isNotEmpty(keepFiles)) {
                        List<String> keepFileList = Arrays.asList(keepFiles.split(","));
                        if (keepFileList.size() > 0) {
                            measure.getKeepList().addAll(keepFileList);
                        }
                    }
                    List<String> keepList = measure.getKeepList();
                    if (null != keepList && keepList.size() > 0) {
                        measure.setAttachment(new Gson().toJson(keepList));
                    } else {
                        measure.setAttachment("");
                    }
                    // 删除的附件地址
                    String delFiles = measure.getDelFiles();
                    if (StringUtils.isNotEmpty(delFiles)) {
                        List<String> delFileList = Arrays.asList(delFiles.split(","));
                        if (delFileList.size() > 0) {
                            for (String delFile : delFileList) {
                                clientWrapper.deleteFile(delFile.split("#")[0]);
                            }
                        }
                    }
                    measure.setId(DefaultIdGenerator.getInstance().generateLongId());
                    measure.setDangerousOperationId(bean.getId());
                }
            }
            // 更新安全措施，先删除原有数据，再重新添加
            dangerousOperationRelationMapper.deleteSafeByDangerousOperationId(bean.getId());
            dangerousOperationRelationMapper.batchInsertSafe(bean.getSafetyMeasureList());

            if (request.getParameter("attachmentFileSize") != null && Integer.parseInt(request.getParameter("attachmentFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("attachmentFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("attachmentFiles" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                bean.setAttachmentFiles(files);
            }

            if (null != bean.getAttachmentFiles() && bean.getAttachmentFiles().length > 0) {
                for (MultipartFile file : bean.getAttachmentFiles()) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    bean.getKeepList().add(url + "#" + fileName);
                }
            }
            // 要保留的附件管理
            String keepFiles = bean.getKeepFiles();
            if (StringUtils.isNotEmpty(keepFiles)) {
                String[] keepArray = keepFiles.split(",");
                bean.getKeepList().addAll(Arrays.asList(keepArray));
            }
            List<String> keepList = bean.getKeepList();
            if (null != keepList && keepList.size() > 0) {
                bean.setAttachment(new Gson().toJson(keepList));
            }
            // 删除的附件地址
            String delFiles = bean.getDelFiles();
            if (StringUtils.isNotEmpty(delFiles)) {
                String[] delArray = delFiles.split(",");
                for (String delUrl : delArray) {
                    clientWrapper.deleteFile(delUrl.split("#")[0]);
                }
            }
            // 作业编制人签字
            if (request.getParameter("editOperationFileSize") != null && Integer.parseInt(request.getParameter("editOperationFileSize")) > 0) {
                int size = Integer.parseInt(request.getParameter("editOperationFileSize").toString());
                MultipartFile[] files = new MultipartFile[size];
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < size; i++) {
                            List<MultipartFile> fileList = standardMultipartHttpServletRequest.getFiles("editOperationFile" + i);
                            if (fileList.size() > 0) {
                                files[i] = fileList.get(0);
                            }
                        }
                    }
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String url = clientWrapper.uploadFile(file);
                        //获得文件名
                        String fileName = file.getOriginalFilename();
                        keepList.add(url + "#" + fileName);
                    }
                    if (keepList.size() > 0) {
                        bean.setEditOperationSignature(new Gson().toJson(keepList));
                    }
                }
            }
            // 更新作业票记录
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(new Date());
            Integer value = factory.getMapper(OperationActivityMapper.class).updateOperationTicket(bean);

            if (value > 0 && bean.getStatus() == 1) {
                String templateKey = getTemplateKey(bean.getOperationTicketType());
                // 启动流程
                if (null == templateKey) {
                    factory.close();
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("未找到流程模板");
                    return msg;
                }
                Boolean startAudit = startAudit(bean, user, "流程待审批", "作业活动-作业票流程", templateKey);
                if (!startAudit) {
                    deleteKeepFile(bean);
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("作业活动-作业票流程启动失败");
                    return msg;
                } else {
                    deleteDelFile(bean);
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("作业活动-作业票提交成功");
                    msg.setData(value);
                    return msg;
                }
            }
            if (value > 0) {
                OperationTicketQuery query = new OperationTicketQuery();
                query.setOperationActivityId(bean.getOperationActivityId());
                List<OperationTicket> list = mapper.selectOperationTicket(query);
                if (list != null && list.size() > 0) {
                    String collect = list.stream().map(OperationTicket::getOperationTicketTypeName).distinct().collect(Collectors.joining(","));
                    mapper.updateOperationActivityType(bean.getOperationActivityId(), collect);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error("修改作业票失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "修改作业票失败", null);
        }
        return msg;
    }

    @Override
    @TaskAnnotation("confirm")
    public MessageBean confirm(SessionFactory factory, OperationTicket bean) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "确认作业票完工成功", null);
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);

        try {
            OperationTicket operationTicket = mapper.selectOperationTicketById(bean.getId());
            if (operationTicket == null) {
                logger.error("作业票数据不存在");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "作业票数据不存在", null);
            }
            if (operationTicket.getStatus() != 2) {
                logger.error("非生效中状态下的作业票不能确认完工");
                factory.close();
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "非生效中状态下的作业票不能确认完工", null);
            }

            List<String> keepList = new ArrayList<>();
            if (null != bean.getCompletionConfirmSignatureFiles() && bean.getCompletionConfirmSignatureFiles().length > 0) {
                for (MultipartFile file : bean.getCompletionConfirmSignatureFiles()) {
                    String url = clientWrapper.uploadFile(file);
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    keepList.add(url + "#" + fileName);
                }
                if (keepList.size() > 0) {
                    operationTicket.setCompletionConfirmSignature(new Gson().toJson(keepList));
                }
            }
            operationTicket.setCompletionConfirm(bean.getCompletionConfirm());
            operationTicket.setCompletionConfirmName(bean.getCompletionConfirmName());
            operationTicket.setCompletionTime(bean.getCompletionTime());
            operationTicket.setCompletionDescription(bean.getCompletionDescription());

            operationTicket.setStatus(4);
            Integer update = mapper.updateOperationTicket(operationTicket);
            if (update <= 0) {
                factory.close(false);
                logger.error("确认完工失败");
                return MessageBean.create(BusinessCode.FAILURE.getCode(), "确认完工失败", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error("确认作业票完工失败");
            factory.close(false);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "确认作业票完工失败", null);
        }
        return msg;
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List<OperationTicket>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
            DangerousOperationRelationMapper dangerousOperationRelationMapper = factory.getMapper(DangerousOperationRelationMapper.class);
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    List<OperationTicket> list = new ArrayList<>();
                    for (String id : idList) {
                        OperationTicket operationTicket = mapper.selectOperationTicketById(id);

                        // 查询气体分析
                        if (operationTicket.getIncludeGas() != null && operationTicket.getIncludeGas() == 1) {
                            List<GasAnalysis> gasAnalyses = Optional.of(mapper.selectGasAnalysisByOperationTicketId(id)).orElse(new ArrayList<>());
                            operationTicket.getGasAnalysisList().addAll(gasAnalyses);
                        }

                        // 查询安全措施
                        List<SafetyMeasure> safetyMeasures = Optional.of(dangerousOperationRelationMapper.getSafetyByDangerousId(id)).orElse(new ArrayList<>());
                        operationTicket.getSafetyMeasureList().addAll(safetyMeasures);
                        list.add(operationTicket);
                    }
                    msg.setData(list);
                }
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("id不能为空");
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean flowSignSave(SessionFactory factory, StaffBean user, String id, MultipartFile[] files) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "签名提交成功", Integer.class);
        try {
            OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
            // 获取作业票详情
            OperationTicket operationTicket = mapper.selectOperationTicketById(id);
            //获取流程数据
            // 根据业务id和更新时间来获取审批Audit数据
            List<String> idLists = new ArrayList<>();
            idLists.add(id);
            Audit audit = auditService.queryByBusinessIds(new Gson().toJson(idLists), operationTicket.getUpdateTime());
            // 获取流程审批历史轨迹
            MessageBean<?> history = flowService.history(audit.getSetCode(), audit.getTemplateKey(), audit.getId());
            String templateKey = audit.getTemplateKey();
            if (0 == history.getCode() && history.getData() != null) {
                List<Map> historys = (List<Map>) history.getData();
                if (historys != null && historys.size() > 0) {
                    List<String> signList = new ArrayList<>();
                    if (null != files && files.length > 0) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            //获得文件名
                            String fileName = file.getOriginalFilename();
                            signList.add(url + "#" + fileName);
                        }
                    }
                    String nowNodeCode = null;
                    Map map = historys.get(historys.size() - 1);
                    if (map.containsKey("tasks")) {
                        List nowMapList = (List) map.get("tasks");
                        if (CollectionUtils.isNotEmpty(nowMapList)) {
                            Map nowMap = (Map) nowMapList.get(0);
                            if (nowMap.containsKey("taskCode")) {
                                nowNodeCode = nowMap.get("taskCode").toString();
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(nowNodeCode)) {
                        if ("operation_ticket1_creation".equals(templateKey) || "operation_ticket1_1creation".equals(templateKey)) {
                            if (PROCESSTASK1.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getApproveOperationChargeSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getApproveOperationChargeSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setApproveOperationChargeSignature(new Gson().toJson(signList));
                            } else if (PROCESSTASK2.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getWorkUnitSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getWorkUnitSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setWorkUnitSignature(new Gson().toJson(signList));
                            } else if (PROCESSTASK3.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getSafetyManageDeptSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getSafetyManageDeptSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setSafetyManageDeptSignature(new Gson().toJson(signList));
                            } else if (PROCESSTASK4.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getWorkApproverSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getWorkApproverSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setWorkApproverSignature(new Gson().toJson(signList));
                            }
                        } else if ("operation_ticket2_creation".equals(templateKey) || "operation_ticket2_1creation".equals(templateKey)) {
                            if (PROCESSTASK1.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getApproveOperationChargeSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getApproveOperationChargeSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setApproveOperationChargeSignature(new Gson().toJson(signList));
                            } else if (PROCESSTASK2.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getElectricConsumeUnitSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getElectricConsumeUnitSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setElectricConsumeUnitSignature(new Gson().toJson(signList));
                            } else if (PROCESSTASK3.equals(nowNodeCode)) {
                                if (StringUtils.isNotEmpty(operationTicket.getElectricDistributionUnitSignature())) {
                                    List<String> array = JSONObject.parseArray(operationTicket.getElectricDistributionUnitSignature(), String.class);
                                    signList.addAll(array);
                                }
                                operationTicket.setElectricDistributionUnitSignature(new Gson().toJson(signList));
                            }
                        }
                    }
                }
                Integer integer = mapper.updateOperationTicket(operationTicket);
                msg.setData(integer);
            }
            return msg;
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    private String getTemplateKey(String ticketType) {
        if ("2".equals(ticketType)) {
            return "operation_ticket2_creation";
        } else {
            return "operation_ticket1_creation";
        }
    }


    private String getTemplateKeyByQrCode(String ticketType) {
        if ("2".equals(ticketType)) {
            return "operation_ticket2_1creation";
        } else {
            return "operation_ticket1_1creation";
        }
    }


    /**
     * 提交作业票启动流程
     *
     * @param bean        危险作业
     * @param user        当前登陆人
     * @param title       流程标题、名称
     * @param description 流程描述
     * @param templateKey 流程模板
     * @return
     * @throws InvalidSystemClockException
     * @throws GetHardwareIdFailedException
     */
    private Boolean startAudit(OperationTicket bean, StaffBean user, String
            title, String description, String templateKey) throws InvalidSystemClockException, GetHardwareIdFailedException {
        Audit audit = new Audit();
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        audit.setUpdateTime(bean.getUpdateTime());
        audit.setUpdateUser(bean.getUpdateUserName());
        audit.setAddUser(bean.getUpdateUserName());
        audit.setAddTime(bean.getUpdateTime());
        audit.setFlowType(1);
        audit.setOperation(1);
        audit.setTarget(OperationActivityServiceImpl.class.getName());
        audit.setFlowName("作业活动-作业票流程待审批");
        audit.setTitle(bean.getOperationTicketTypeName() + title);
        audit.setCorpCode(bean.getCorpCode());
        audit.setInitiatorCode(user.getCode());
        audit.setDescription(description);
        audit.setState(1);
        audit.setTemplateKey(templateKey);
        // 模板组code
        audit.setSetCode("operation_ticket");
        audit.setInitiatorAccount(user.getUserid());
        List<String> idLists = new ArrayList<>();
        idLists.add(bean.getId());
        audit.setBusinessIds(new Gson().toJson(idLists));
        // 设置流程审批节点
        Map businessMap = SetWorkFlowNode(templateKey, bean);
        return flowManagement.initFlow(user, audit, businessMap);
    }

    private Boolean startAuditByQrCode(OperationTicket bean, StaffBean user, List<String> approverList, String
            title, String description, String templateKey) throws InvalidSystemClockException, GetHardwareIdFailedException {
        Audit audit = new Audit();
        audit.setId(DefaultIdGenerator.getInstance().generateLongId());
        audit.setUpdateTime(bean.getUpdateTime());
        audit.setUpdateUser(bean.getUpdateUserName());
        audit.setAddUser(bean.getUpdateUserName());
        audit.setAddTime(bean.getUpdateTime());
        audit.setFlowType(1);
        audit.setOperation(1);
        audit.setTarget(OperationActivityServiceImpl.class.getName());
        audit.setFlowName("作业活动-作业票流程待审批");
        audit.setTitle(bean.getOperationTicketTypeName() + title);
        audit.setCorpCode(bean.getCorpCode());
        audit.setInitiatorCode(user.getCode());
        audit.setDescription(description);
        audit.setState(1);
        audit.setTemplateKey(templateKey);
        // 模板组code
        audit.setSetCode("operation_ticket");
        audit.setInitiatorAccount(user.getUserid());
        List<String> idLists = new ArrayList<>();
        idLists.add(bean.getId());
        audit.setBusinessIds(new Gson().toJson(idLists));
        Map<String, Object> businessMap = new HashMap<>();
        StringBuilder codes = new StringBuilder();
        for (String code : approverList) {
            codes.append(code).append(",");
        }
        businessMap.put("approver", codes.substring(0, codes.lastIndexOf(",")));
        return flowManagement.initFlow(user, audit, businessMap);
    }

    private Map SetWorkFlowNode(String ticketType, OperationTicket bean) {
        Map<String, Object> businessMap = new HashMap<>();
        if (templateKeys.get(1).equals(ticketType)) {
            businessMap.put("approver", StringUtils.isNotEmpty(bean.getApproveOperationCharge()) ? bean.getApproveOperationCharge().split("_")[1] : "");
            businessMap.put("workUnit", StringUtils.isNotEmpty(bean.getWorkUnit()) ? bean.getWorkUnit().split("_")[1] : "");
            businessMap.put("safetyManageDept", StringUtils.isNotEmpty(bean.getSafetyManageDept()) ? bean.getSafetyManageDept().split("_")[1] : "");
            businessMap.put("workApprover", StringUtils.isNotEmpty(bean.getWorkApprover()) ? bean.getWorkApprover().split("_")[1] : "");
        } else if (templateKeys.get(2).equals(ticketType)) {
            businessMap.put("approver", StringUtils.isNotEmpty(bean.getApproveOperationCharge()) ? bean.getApproveOperationCharge().split("_")[1] : "");
            businessMap.put("electricConsumeUnit", StringUtils.isNotEmpty(bean.getElectricConsumeUnit()) ? bean.getElectricConsumeUnit().split("_")[1] : "");
            businessMap.put("electricDistributionUnit", StringUtils.isNotEmpty(bean.getElectricDistributionUnit()) ? bean.getElectricDistributionUnit().split("_")[1] : "");
        }
        return businessMap;
    }

    // 删除保留文件
    public void deleteKeepFile(OperationTicket bean) {
        // 附件
        List<String> keepList = bean.getKeepList();
        if (null != keepList && keepList.size() > 0) {
            if (StringUtils.isNotEmpty(bean.getKeepFiles())) {
                List<String> keeps = Arrays.asList(bean.getKeepFiles().split("[,，]"));
                for (String url : keepList) {
                    if (!keeps.contains(url)) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                }
            } else {
                for (String url : keepList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
        }
    }

    public void deleteDelFile(OperationTicket bean) {
        // 删除的附件地址
        String delFiles = bean.getDelFiles();
        if (StringUtils.isNotEmpty(delFiles)) {
            String[] delArray = delFiles.split("[,，]");
            for (String delUrl : delArray) {
                clientWrapper.deleteFile(delUrl.split("#")[0]);
            }
        }
    }

    public void deleteFile(String delFiles) {
        if (StringUtils.isNotEmpty(delFiles)) {
            String[] delArray = delFiles.split("[,，]");
            for (String delUrl : delArray) {
                clientWrapper.deleteFile(delUrl.split("#")[0]);
            }
        }
    }

    /**
     * 编号生成 格式（例2020-08-24-001）
     *
     * @param factory 数据库连接
     * @return
     */
    public String getCode(SessionFactory factory) {
        OperationActivityMapper mapper = factory.getMapper(OperationActivityMapper.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder sb = new StringBuilder();
        // 获取当前日期
        String date = sdf.format(new Date());
        StringBuilder builder = sb.append(date).append("-");
        // 根据当前时间查询已存在的最大code
        String maxCode = mapper.queryMaxCode(builder.toString());
        if (null == maxCode) {
            return builder.append("001").toString();
        }
        // 截取最后三位
        String substring = maxCode.substring(maxCode.length() - 3);
        //末位加1
        long lastNum = Long.parseLong("1" + substring) + 1;
        // 替换最后三位
        maxCode = maxCode.substring(0, maxCode.length() - 3) + (lastNum + "").substring(1);
        return maxCode;
    }

    // 流程审批结束后的操作
    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String operationTicketId = idList.get(0);
                if (StringUtils.isNotEmpty(operationTicketId)) {
                    OperationTicket operationTicket = factory.getMapper(OperationActivityMapper.class).selectOperationTicketById(operationTicketId);
                    if (operationTicket != null && operationTicket.getStatus() == 1) {
                        //新增作业票流程审核通过后，将状态设为2(生效中)
                        operationTicket.setStatus(2);
                        operationTicket.setEffectiveTime(new Date());
                    }
                    factory.getMapper(OperationActivityMapper.class).updateOperationTicket(operationTicket);
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    // 删除走流程审批通过后的流程操作
    @Override
    public void discardApproval(Audit audit) {

    }

    // 流程审批不通过的操作
    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                String operationTicketId = idList.get(0);
                if (StringUtils.isNotEmpty(operationTicketId)) {
                    OperationTicket operationTicket = factory.getMapper(OperationActivityMapper.class).selectOperationTicketById(operationTicketId);
                    if (operationTicket != null && operationTicket.getStatus() == 1) {
                        // 新增提交审核不通过，状态改为草稿
                        operationTicket.setStatus(0);
                    }
                    factory.getMapper(OperationActivityMapper.class).updateOperationTicket(operationTicket);
                    factory.close();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        }
    }

    // 流程驳回操作
    @Override
    public void reject(Audit audit, List<String> userIdList) {

    }

    // 流程提交通过操作
    @Override
    public void passApproval(Integer operation, Audit audit) {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(OperationActivityServiceImpl.class.getName(), this);
    }
}
